﻿using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System;
using System.Configuration;
using Xcj.Mes.Core.Logger;
using Xcj.Mes.WholeLine.DataBase.Entity;

namespace Xcj.Mes.WholeLine.DataBase.Context
{
    // SQL server 需要添加包
    // Microsoft.EntityFrameworkCore 
    // Microsoft.EntityFrameworkCore.SqlServer 
    // Microsoft.EntityFrameworkCore.Tools 
    // System.Data.Entity.Core.EntityClient;
    // Newtonsoft.Json：用于Json格式转换 

    public class SQLServerContext : DbContext
    {
        public static SQLServerContext GetInstance()
        {
            SQLServerContext dbContext = new SQLServerContext();
            try
            {
                var connectionString = GetConnectionString(ConnectionStringPattern.ByConfiguration);
                var optionsBuilder = new DbContextOptionsBuilder<SQLServerContext>();
                optionsBuilder.EnableServiceProviderCaching(true);

                // 连接SqlServer
                optionsBuilder.UseSqlServer(connectionString);
                // 连接MySql
                //builder.UseMySql(ConnString,new MySqlServerVersion(new Version()));

                dbContext = new SQLServerContext(optionsBuilder.Options);
                
                dbContext?.Database?.EnsureCreated();

                return dbContext;
            }
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                dbContext?.Database?.CloseConnection();
                dbContext?.Dispose();
            }

            return null;
        }

        private static string GetConnectionString(ConnectionStringPattern pattern)
        {
            string connectionString = string.Empty;

            switch (pattern)
            {
                case ConnectionStringPattern.ByString:
                    //使用本地数据库路径：
                    //string connectionString = "Data Source=|DataDirectory|DATABASE_NAME.mdf;Integrated Securit
                    //string connectionString = "Data Source=SERVER_NAME;Initial Catalog=DATABASE_NAME;User ID=USER_ID;Password=PASSWORD;";
                    // connectionString = "Data Source=.;Initial Catalog=ZH_HG_WholeLineDB;Integrated Security=false;User ID=sa;Password=XCJ123456";
                    // connectionString = "Data Source=.;Initial Catalog=ZH_HG_WholeLineDB;Persist Security Info=True;TrustServerCertificate=True;User ID=sa;Password=XCJ123456;";
                    //connectionString = "Server=.;Initial Catalog=ZH_HG_WholeLineDB;Persist Security Info=True;TrustServerCertificate=True;User ID=sa;Password=XCJ123456;";
                    connectionString = "Server=; Database=ZH_HG_WholeLineDB; Trusted_Connection=SSPI; TrustServerCertificate=true;";
                    break;

                case ConnectionStringPattern.BySqlConnectionStringBuilder:
                    SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
                    sqlBuilder.DataSource = ".";
                    sqlBuilder.InitialCatalog = "ZH_HG_WholeLineDB";
                    sqlBuilder.IntegratedSecurity = false;
                    //sqlBuilder.UserID = "CENJE";
                    sqlBuilder.UserID = "sa";
                    sqlBuilder.Password = "XCJ123456";
                    connectionString = sqlBuilder.ConnectionString;
                    break;

                case ConnectionStringPattern.ByConfiguration:
                    connectionString = ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;
                    break;

                default:
                    throw new Exception("Pattern Error");
            }

            return connectionString;
        }

        /// <summary>
        /// 默认构造函数 使用方法与原来一样
        /// </summary>
        private SQLServerContext() : base() { }

        private SQLServerContext(DbContextOptions<SQLServerContext> options) : base(options) { }

        /// <summary>
        /// 无主键 视图
        /// </summary>
        /// <param name="builder"></param>
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            //实体配置类在哪里，找到BOOkconfig这个类,加载所有的IEntityTypeConfiguration<>
            builder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);//加载当前程序集
            
            //指定主键字段，如果主键名称是id/Id/ID，可以省略
            //builder.Entity<Account>().HasKey("ID");
        
            //指定为无主键或视图，不然可能会报错
            //builder.Entity<view1>().HasNoKey();
            //builder.Entity<view2>().HasNoKey();
        }
        
        /// <summary>
        /// 配置连接字符串，每次访问数据库之前会自动执行此方法，在这里配置连接字符串
        /// 相当于连接前事件
        /// 使用 IOC 注入的方式不实现此方法
        /// </summary>
        /// <param name="builder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder builder)
        {
            base.OnConfiguring(builder);
        }

        public DbSet<AccountEntity> Account { get; set; }
        public DbSet<AlarmConfigEntity> AlarmConfig { get; set; }
        public DbSet<AlarmEntity> Alarm { get; set; }
        public DbSet<BatchEntity> Batch { get; set; }
        public DbSet<DeviceConfigEntity> DeviceConfig { get; set; }
        public DbSet<LoginEntity> Login { get; set; }
        public DbSet<MaintenanceEntity> Maintenance { get; set; }
        public DbSet<NotGoodEntity> NotGood { get; set; }
        public DbSet<PlcAddressEntity> PlcAddress { get; set; }
        public DbSet<PlcConfigEntity> PlcConfig { get; set; }
        public DbSet<QuickWearPartEntity> QuickWearPart { get; set; }

        public enum ConnectionStringPattern
        {
            ByString,
            BySqlConnectionStringBuilder,
            ByConfiguration
        }
    }
}
